package com.ityls.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
import co.elastic.clients.elasticsearch.core.search.FieldSuggester;
import co.elastic.clients.elasticsearch.core.search.Suggester;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import com.ityls.domain.News;
import com.ityls.repository.NewsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class NewsService {
    @Autowired
    private ElasticsearchClient client;

    @Autowired
    private NewsRepository repository;

    // 自动补齐
    public List<String> autoSuggest(String keyword) throws IOException {
        // 1.创建自动补齐查询条件
        Suggester suggester = Suggester.of(
                s -> s.suggesters("prefix_suggestion", FieldSuggester.of(
                        fs -> fs.completion(
                                cs -> cs.skipDuplicates(true)
                                        .size(10)
                                        .field("tags")
                        )
                )).text(keyword)
        );

        // 2.自动补齐查询
        SearchResponse<Map> response = client.search(s -> s.index("news").suggest(suggester), Map.class);

        // 3.处理查询结果
        Map<String, List<Suggestion<Map>>> resultMap = response.suggest();
        List<Suggestion<Map>> suggestionList = resultMap.get("prefix_suggestion");
        Suggestion<Map> suggestion = suggestionList.get(0);
        List<CompletionSuggestOption<Map>> resultList = suggestion.completion().options();

        List<String> result = new ArrayList<>();
        for (CompletionSuggestOption<Map> completionSuggestOption : resultList) {
            String text = completionSuggestOption.text();
            result.add(text);
        }
        return result;
    }

    // 查询关键字
    public List<News> highLightSearch(String keyword){
        List<SearchHit<News>> result = repository.findByTitleMatchesOrContentMatches(keyword, keyword);
        // 处理结果，封装为News类型的集合
        List<News> newsList = new ArrayList();
        for (SearchHit<News> newsSearchHit : result) {
            News news = newsSearchHit.getContent();
            // 高亮字段
            Map<String, List<String>> highlightFields = newsSearchHit.getHighlightFields();
            if (highlightFields.get("title") != null){
                news.setTitle(highlightFields.get("title").get(0));
            }
            if (highlightFields.get("content") != null){
                news.setContent(highlightFields.get("content").get(0));
            }
            newsList.add(news);
        }
        return newsList;
    }
}
